using Avalonia.Controls;
using Avalonia.Threading;
using DebounceThrottle;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Windows;

namespace AvaMaid.Neo.Views
{
    public partial class EventCodeGenView : UserControl
    {
        private DebounceDispatcher _dispatcher = new DebounceDispatcher(TimeSpan.FromMilliseconds(200));

        public EventCodeGenView()
        {
            InitializeComponent();
        }


        public async void PART_EventCopyButton_Click(object sender, Avalonia.Interactivity.RoutedEventArgs args)
        {
            Clipboard.SetText(PART_EventText.Text);
        }


        private string GenCode(string className, string eventName, string methodName)
        {
            if (string.IsNullOrWhiteSpace(className)) return string.Empty;
            if (string.IsNullOrWhiteSpace(eventName)) return string.Empty;
            if (string.IsNullOrWhiteSpace(methodName)) return string.Empty;

            var avaloniaAssemblies = AppDomain.CurrentDomain.GetAssemblies().Where(i => i.GetName().Name.Contains("Avalonia"));
            var controlClass = avaloniaAssemblies.SelectMany(i => i.ExportedTypes).FirstOrDefault(i => i.Name == className);

            if (controlClass is null) return string.Empty;

            var eventInfo = controlClass.GetEvent(eventName);

            if (eventInfo is null) return string.Empty;

            var delegateType = eventInfo.EventHandlerType;


            // 获取委托的参数信息
            var invokeMethod = delegateType.GetMethod("Invoke");
            var parameters = invokeMethod.GetParameters();
            var returnType = invokeMethod.ReturnType;
            var handlerCode = GenerateHandlerCode(delegateType, parameters, returnType, methodName);


            return handlerCode;
        }
        /// <summary>
        /// 生成事件处理方法的代码字符串
        /// </summary>
        private static string GenerateHandlerCode(Type delegateType, ParameterInfo[] parameters, Type returnType, string eventName)
        {
            // 构建参数列表
            List<string> paramList = new List<string>();
            foreach (var param in parameters)
            {
                paramList.Add($"{param.ParameterType.FullName} {param.Name}");
            }
            string parametersString = string.Join(", ", paramList);

            // 构建参数输出代码
            List<string> paramOutputs = new List<string>();
            foreach (var param in parameters)
            {
                paramOutputs.Add($"\"{param.Name}: \" + {param.Name}?.ToString()");
            }


            // 生成完整的代码
            return
$@"public async void {eventName}({parametersString})
{{
    throw new NotImplementedException();
}}";
        }

        private void TextBox_TextChanged(object? sender, Avalonia.Controls.TextChangedEventArgs e)
        {
            UpdateCode();
        }

        private void UpdateCode()
        {
            _dispatcher.Debounce(() =>
            {
                Dispatcher.UIThread.Invoke(() =>
                {
                    GenerateEventCode(PART_ClassTB.Text, PART_EventNameTB.Text, PART_MethodNameTB.Text);
                });
            });
        }

        private void GenerateEventCode(string className, string eventName, string methodName)
        {
            PART_EventText.Text = GenCode(className, eventName, methodName);
        }
    }
}
